package com.chenjun.designpattern.structural.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class 动态代理工厂类
{
	public static void main(String[] args)
	{
		AbstractTatget targetProxy = new DynamicProxyFactory<ConcreteTarget>().getProxy(ConcreteTarget.class);
		targetProxy.call();
	}
}

interface AbstractTatget
{
	public void call();
}

class ConcreteTarget implements AbstractTatget
{
	@Override
	public void call()
	{
		System.out.println("ConcreteTarget.call() is called......... ");
	}
}

/**
 * 泛型参数T = 被代理类实现的接口类型
 * @author Administrator
 *
 * @param <T>
 */
class DynamicProxyFactory<T>
{
	@SuppressWarnings("unused")
	private T proxy;

    @SuppressWarnings("unchecked")
	public T getProxy(final Class <? extends T> clazz)
	{
    	Class<?>[] superClazzArray = clazz.getInterfaces();
		return (T) (Proxy.newProxyInstance(clazz.getClassLoader(), superClazzArray, new InvocationHandler()
		{
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
			{
				return method.invoke(clazz.newInstance(), args);
			}
		}));
	}
}
